import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from './AuthContext';
import { increment } from './store/counterSlice';
import { useAppDispatch } from './store/hooks';

function getCount(initVal: number) {
  console.log("getCount....")
  return initVal
}

function Counter2() {
  const [count, setCount] = useState(() => getCount(0));
  const { user, login, logout } = useAuth()
  const dispatch = useAppDispatch()

  const prevCountRef = useRef<number>();
  useEffect(() => {
    console.log("effect...", count);
    prevCountRef.current = count;
  });
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
    return () => {
      console.log('unmounted....', count)
    }
  });
  const prevCount = prevCountRef.current;
  console.log("render...counter2", count, prevCountRef.current);
  return (
    <div style={{margin: '20px', background: '#efefef'}}>
      <h1>Count 2 Now: {count}, before: {prevCount}，users: {JSON.stringify(user || {})}</h1>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>&nbsp;&nbsp;
      <button onClick={login}>
        login
      </button>&nbsp;&nbsp;
      <button onClick={logout}>
        logout
      </button>&nbsp;&nbsp;
      <button onClick={() => dispatch(increment())}>increment: + 1</button>&nbsp;&nbsp;
      </div>
  );
}

export default Counter2;
